package com.delong.spring.handler.market;

import java.util.List;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.delong.cache.AppCache;
import com.delong.model.market.Pictures;
import com.delong.model.market.ScheduleContent;
import com.delong.service.market.PicturesService;
import com.delong.service.market.ScheduleContentService;
import com.delong.service.market.SourceBaseService;

@Controller
@RequestMapping("/schedulecontent")
public class ScheduleContentController {
	private ScheduleContentService service = new ScheduleContentService();
	private PicturesService picturesService = new PicturesService();
	private SourceBaseService sourceBaseService = new SourceBaseService();

	@RequestMapping("/list")
	public String getScheduleList(Map<String, Object> model, ServletRequest req,
			@RequestParam(value = "schedule_id", defaultValue = "0") int scheduleId,
			@RequestParam(value = "page_id", defaultValue = "0") int pageId) {
		HttpServletRequest request = (HttpServletRequest) req;
		model.put("username", request.getSession().getAttribute("username"));
		model.put("sources", this.sourceBaseService.getALLElement());
		model.put("schedule_id", scheduleId);
		model.put("page_id", pageId);
		return "market/ScheduleContent";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public String scheduleContentAdd(Map<String, Object> model,
			@RequestParam(value = "page_id", defaultValue = "0") int paggId,
			@RequestParam(value = "resource", defaultValue = "") String data,
			@RequestParam(value = "schedule_id", defaultValue = "") int scheduleId,
			@RequestParam(value = "id", defaultValue = "0") int id,
			@RequestParam(value = "type", defaultValue = "0") int scheduleTypeId,
			@RequestParam(value = "title", defaultValue = "") String title,
			@RequestParam(value = "order", defaultValue = "") int scheduleOrder,
			@RequestParam(value = "source", defaultValue = "") String source,
			@RequestParam(value = "row_num", defaultValue = "1") int rowNum) {

		ScheduleContent element = new ScheduleContent();
		element.setCreatedate(new Date());
		element.setSchedule_id(scheduleId);
		element.setSchedule_type_id(scheduleTypeId);
		element.setTitle(title);
		element.setSchedule_order(scheduleOrder);
		JSONArray jsonData = JSONArray.parseArray(data);

		if (id == 0) {
			String content = "";
			if (scheduleTypeId == 1 || scheduleTypeId == 2 || scheduleTypeId == 3) {

				content = convertToObject(jsonData);
				switch (scheduleTypeId) {
				case 1:
					rowNum = 4;
					break;
				case 2:
					rowNum = 1;
					break;
				case 3:
					rowNum = 2;
					break;
				}
			} else {
				content = source;

			}
			element.setRow_num(rowNum);
			element.setContent(content.toString());
			this.service.addElement(element);
		} else {
			String content = "";
			if (scheduleTypeId == 1 || scheduleTypeId == 2 || scheduleTypeId == 3) {
				ScheduleContent oldElement = this.service.getElement(id);
				String oldContent = oldElement.getContent();
				List<Integer> oldIds = getIds(oldContent);
				this.picturesService.deleteElementByIds(oldIds);
				content = convertToObject(jsonData);
				switch (scheduleTypeId) {
				case 1:
					rowNum = 4;
					break;
				case 2:
					rowNum = 1;
					break;
				case 3:
					rowNum = 2;
					break;
				}
			} else {
				content = source;
			}
			element.setContent(content.toString());
			element.setRow_num(rowNum);

			element.setId(id);
			this.service.updateElement(element);
		}
		// 页面缓存失效
		AppCache cache = new AppCache();
		List<Integer> scheduleIds = new ArrayList<Integer>();
		scheduleIds.add(scheduleId);
		cache.deletePagesByScheduleId(scheduleIds);
		JSONObject result = new JSONObject();
		result.put("code", 0);
		result.put("message", "success");
		return result.toJSONString();
	}

	private String convertToObject(JSONArray jsonData) {
		StringBuffer content = new StringBuffer();
		for (int jsonIndex = 0; jsonIndex < jsonData.size(); jsonIndex++) {
			Pictures element = new Pictures();
			JSONObject obj = jsonData.getJSONObject(jsonIndex);
			element.setIntent_data(obj.getString("target_url"));
			element.setIntent_type(obj.getIntValue("target_type"));
			element.setUrl(obj.getString("img"));
			element.setTitle(obj.getString("text"));
			element.setPic_type(3);
			this.picturesService.addElement(element);
			if (jsonIndex > 0) {
				content.append(",");
			}
			content.append(String.valueOf(element.getId()));

		}

		return content.toString();
	}

	private List<Integer> getIds(String content) {
		List<Integer> pIds = new ArrayList<Integer>();
		if (content == null || content == "")
			return pIds;
		String[] spids = content.split(",");

		for (int i = 0; i < spids.length; i++) {
			pIds.add(Integer.valueOf(spids[i]));
		}
		return pIds;
	}

	@RequestMapping(value = "/getdata", method = RequestMethod.POST)
	@ResponseBody
	public String getAppListData(Map<String, Object> model,
			@RequestParam(value = "schedule_id", defaultValue = "0") int schedule_id,
			@RequestParam(value = "page", defaultValue = "1") int page,
			@RequestParam(value = "rows", defaultValue = "15") int rows) {
		page = page - 1; // List<Schedule> elements =
		List<ScheduleContent> elements = this.service.getListElement(schedule_id, page * rows, rows); // int
																										// total
																										// =
		int total = this.service.getListCount(schedule_id);
		JSONObject result = new JSONObject();
		result.put("rows", elements);
		result.put("total", total);
		return result.toJSONString();
	}

	@RequestMapping("/deleteElement")

	@ResponseBody
	public String changePageElementStatus(Map<String, Object> model,

	@RequestParam(value = "id", defaultValue = "0") int id,

	@RequestParam(value = "scheduleId", defaultValue = "0") int scheduleId) {

		JSONObject result = new JSONObject();
		if (id > 0) {
			result.put("code", 0);
			this.service.changeStatus(id);
			AppCache cache = new AppCache();
			List<Integer> scheduleIds = new ArrayList<Integer>();
			scheduleIds.add(scheduleId);
			cache.deletePagesByScheduleId(scheduleIds);
		} else {
			result.put("code", 1);
		}

		return result.toJSONString();
	}

	@RequestMapping("/getelement")
	@ResponseBody
	public String getElement(Map<String, Object> model, @RequestParam(value = "id", defaultValue = "0") int id) {

		ScheduleContent element = this.service.getElement(id);
		String content = element.getContent();
		List<Integer> pIds = getIds(content);
		// System.out.println(pIds.size());
		List<Pictures> listPicture = this.picturesService.getElementsByIds(pIds);
		// System.out.println(listPicture.size());
		element.setPictures(listPicture);
		JSONObject result = new JSONObject();
		result.put("code", 0);
		result.put("data", element);
		return result.toJSONString();
	}

}
